home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news!enno
- From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
- Newsgroups: comp.lang.c++
- Subject: Re: Template casting problem
- Date: 27 Jan 1996 12:36:45 GMT
- Organization: Fachbereich Informatik, TH Darmstadt
- Distribution: world
- Message-ID: <ENNO.96Jan27133645@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- References: <41@site73.site73.ping.at>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- In-reply-to: mgeramb@site73.site73.ping.at's message of Thu, 25 Jan 1996 08:48:52 GMT
-
- In article <41@site73.site73.ping.at> mgeramb@site73.site73.ping.at (Michael Geramb) writes:
-
- Here is a C++ problem that I never managed to solve.
-
- Imagine you create a template of a class :
-
- template <class T> class A
- {
- ...
- };
-
- This gives a family of classes (instances), say:
-
- A<short>, A<int>, A<float> etc, which may coexist in one function.
- Then, a problem arises how to cast one instance to another.
-
- As a more concrete example, one may imagine a template CVector which
- generates short, integer, float and double instances.
- It also generates a very natural (to my mind) wish to cast
- one instance to another.
-
- It's possible (at least in theory) to provide a templated conversion
- operator:
-
- template<class S> class A {
- ...
- template<class T> operator A<T>() const;
- ...
- };
-
- However the todays compilers will reject this code. In the meantime
- an auxilary generic function should do the job. If 'A' is an array
- class with overloaded 'operator []' and a member-function 'Length'
- the appropriate function may look like:
-
- template<class S,class T> A<T> Convert(const A<S>& source) {
- A<T> target(source.Length());
- for (int i=0; i<source.Length(); i++)
- target[i]=(T)source[i];
- return target;
- }
-
- This function requieres that objects of type S could be converted to
- objects type T. If S is not a builtin type you have to provide an
- appropriate conversion operator. Thus compared to the former solution
- it's not possible to convert e.g. 'an array of an array of floats' to
- 'an array of an array of ints'. I think an implementation that uses
- template-specialization can remove this restriction.
-
- Enno
-